<template>
  <a-modal
    :width="'100%'"
    :style="{ top: 0, paddingBottom: 0 }"
    :bodyStyle="{
      backgroundColor: '#F0F2F5',
      padding: '8px',
      overflow: 'auto'
    }"
    :visible="visible"
    title="设备分组标注"
    :footer="null"
    @update:visible="updateVisible"
  >
    <div class="ele-body ele-body-card">
      <a-row :gutter="16">
        <!-- 左侧设备列表 -->
        <a-col :span="6">
          <a-card :title="data && data.oxtallName ? `${data.oxtallName}相机设备列表` : '牛舍相机设备列表'" :bordered="false">
            <a-input-search
              v-model:value="searchKeyword"
              placeholder="搜索设备ID或macid"
              style="margin-bottom: 16px"
              @search="handleSearch"
            />
            
            <a-spin :spinning="deviceListLoading">
              <a-tree
                v-if="barnTreeData.length > 0"
                :tree-data="barnTreeData"
                :defaultExpandAll="true"
                @select="handleDeviceSelect"
              >
                <template #title="{ title, key, isLeaf }">
                  <div :class="{'device-item': isLeaf, 'selected-device': selectedDeviceId === key}">
                    <div class="device-info">
                      <span v-if="isLeaf" class="device-icon">
                        <camera-outlined />
                        <a-tag :color="getDeviceStatus(key) ? 'success' : 'error'" class="status-tag">
                          {{ getDeviceStatus(key) ? '在线' : '离线' }}
                        </a-tag>
                      </span>
                      {{ title }}
                    </div>
                  </div>
                </template>
              </a-tree>
              <a-empty v-else description="暂无设备数据" />
            </a-spin>
          </a-card>
        </a-col>
        
        <!-- 右侧标注区域 -->
        <a-col :span="18">
          <a-card :bordered="false" :bodyStyle="{ padding: '0' }">
            <template #title>
              <div class="annotation-header">
                <span>设备ID: {{ currentDevice ? currentDevice.recordId : '' }}</span>
                <span v-if="currentDevice && currentDevice.macId">macid: {{ currentDevice.macId }}</span>
                <span v-if="currentDevice && currentDevice.lable1">[{{ currentDevice.lable1 }}]</span>
                <span v-if="currentDevice && currentDevice.ip">[IP:{{ currentDevice.ip }}]</span>
                <a-tag v-if="currentDevice" :color="currentDevice.recordStatus == 1 ? 'success' : 'error'">
                  {{ currentDevice.recordStatus == 1 ? '在线' : '离线' }}
                </a-tag>
              </div>
            </template>
            
            <div v-if="currentDevice" class="annotation-container">
              <!-- 标注区域 -->
              <div class="camera-annotation">
                <!-- 添加提醒信息 -->
                <a-alert
                  class="annotation-tips"
                  type="info"
                  show-icon
                >
                  <template #message>
                    <div class="tips-content">
                      <div class="tip-item">
                        <span>1）先点击"wifi继电器刷新"，同步继电器，再进行标注；2）点击"标注"进入描绘标注模式3）标注结束后，点击"同步到终端"，将标注信息同步到AI相机</span>
                      </div>
                    </div>
                  </template>
                </a-alert>

                <div class="control-panel">
                  <div class="tools">
                    <a-space>
                      <a-button
                        @click="queryWifiList"
                        :loading="queryWifiListRefLoading"
                      >wifi继电器刷新</a-button>
                      <a-button
                        @click="captureImageAction"
                        :loading="capImageActionLoading"
                      >拉取图片</a-button>
                      <a-switch
                        v-model:checked="isAnnotating"
                        checked-children="标注中"
                        un-checked-children="标注"
                        @change="handleAnnotatingChange"
                      />
                      <a-button
                        @click="setMode('rectangle')"
                        :disabled="!isAnnotating"
                      >矩形框</a-button>
                      <a-button
                        @click="setMode('square')"
                        :disabled="!isAnnotating"
                      >正方形框</a-button>
                      <a-button
                        type="primary"
                        @click="handleSync"
                        :loading="syncRefLoading"
                      >同步到终端</a-button>
                      <a-switch
                        v-model:checked="autoRefresh"
                        checked-children="自动刷新"
                        un-checked-children="手动刷新"
                        :disabled="isAnnotating"
                        @change="handleAutoRefresh"
                      />
                      <a-button
                        v-if="!autoRefresh"
                        @click="handleManualRefresh"
                        :loading="refreshLoading"
                      >刷新</a-button>
                    </a-space>
                  </div>

                  <!-- 新增清晰度和缩放比例控制行 -->
                  <div class="image-controls">
                    <a-space>
                      <span>刷新过程中同步取图:</span>
                      <a-switch
                        v-model:checked="autoCapture"
                        checked-children="是"
                        un-checked-children="否"
                      />
                      <span>清晰度:</span>
                      <a-select v-model:value="clarityLevel" style="width: 8cqi" @change="handleClarityChange">
                        <a-select-option value="20">20%</a-select-option>
                        <a-select-option value="30">30%</a-select-option>
                        <a-select-option value="40">40%</a-select-option>
                        <a-select-option value="50">50%</a-select-option>
                      </a-select>

                      <span>缩放比例:</span>
                      <a-select v-model:value="zoomLevel" style="width: 80px" @change="handleZoomChange">
                        <a-select-option value="20">20%</a-select-option>
                        <a-select-option value="30">30%</a-select-option>
                        <a-select-option value="40">40%</a-select-option>
                        <a-select-option value="50">50%</a-select-option>
                      </a-select>
                      <span>携带标注:</span>
                      <a-select v-model:value="withAnnotation" style="width: 60px">
                        <a-select-option value="0">否</a-select-option>
                        <a-select-option value="1">是</a-select-option>
                      </a-select>
                      <span>携带识别结果:</span>
                      <a-select v-model:value="withDetection" style="width: 60px">
                        <a-select-option value="0">否</a-select-option>
                        <a-select-option value="1">是</a-select-option>
                      </a-select>
                      <span>携带时间:</span>
                      <a-select v-model:value="withTimestamp" style="width: 60px">
                        <a-select-option value="0">否</a-select-option>
                        <a-select-option value="1">是</a-select-option>
                      </a-select>
                    </a-space>
                  </div>
                </div>

                <div class="canvas-container">
                  <canvas
                    ref="canvas"
                    @mousedown="startDrawing"
                    @mousemove="drawing"
                    @mouseup="endDrawing"
                  ></canvas>
                </div>

                <!-- 添加设备信息输入弹窗 -->
                <!-- 修改设备信息弹窗 -->
                <a-modal
                  v-model:visible="deviceModalVisible"
                  :title="isEditing ? '编辑设备' : '添加设备'"
                  @ok="handleDeviceSubmit"
                  @cancel="handleDeviceCancel"
                >
                  <template #footer>
                     <!-- 添加新增继电器按钮 -->
                    <a-button key="addRelay" v-if="currentDevice && currentDevice.factory === 'DHUA'" @click="openAddRelayModal">新增继电器</a-button>
                    <!-- 添加刷新继电器按钮 -->
                    <a-button key="refreshRelay" @click="refreshRelayList" :loading="refreshRelayLoading">刷新继电器</a-button>
                    <a-button key="back" @click="handleDeviceCancel">取消</a-button>
                    <a-button v-if="isEditing" key="delete" danger @click="handleDeviceDelete">
                      删除
                    </a-button>
                    <a-button key="submit" type="primary" @click="handleDeviceSubmit">
                      确定
                    </a-button>
                  </template>
                  <a-form :model="deviceForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-form-item label="wifi继电器:" name="deviceType">
                      <a-select
                        show-search
                        v-model:value="deviceForm.relayid"
                        placeholder="请选择wifi继电器"
                        style="width: 100%"
                        :show-arrow="false"
                        :filter-option="false"
                        :not-found-content="null"
                      >
                        <a-select-option v-for="item in relayList" :key="item.relayid" >
                          {{ item.relayid }}
                        </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-form>
                </a-modal>


                <!-- 新增继电器弹窗 -->
                <a-modal
                  v-model:visible="addRelayModalVisible"
                  title="新增继电器"
                  @ok="handleAddRelaySubmit"
                  @cancel="handleAddRelayCancel"
                >
                  <a-form :model="addRelayForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-form-item label="继电器ID:" name="relayid">
                      <a-input v-model:value="addRelayForm.relayid" placeholder="请输入继电器ID" />
                    </a-form-item>
                  </a-form>
                </a-modal>

              </div>
            </div>
            <a-empty v-else description="请从左侧选择设备进行标注" />
          </a-card>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script>
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { CameraOutlined } from '@ant-design/icons-vue';
import { DeviceSprayCameraCaptureimgApi } from "@/api/property/spraycamera/DeviceSprayCameraCaptureimgApi";
import { DeviceSprayCameraSlotApi } from "@/api/property/spraycamera/DeviceSprayCameraSlotApi";
import { DeviceSprayCameraWifirelayApi } from "@/api/property/spraycamera/DeviceSprayCameraWifirelayApi";
import { DeviceCommandDownQueueApi } from "@/api/property/DeviceCommandDownQueueApi";
import { DeviceSprayCameraApi } from "@/api/property/spraycamera/DeviceSprayCameraApi";

export default {
  name: 'DeviceManagerdeviceCameraAssignmentBiaozhu',
  components: {
    CameraOutlined
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 菜单数据
    data: Object
  },
  async mounted() {
    // 加载牛舍下的设备列表
    if (this.visible) {
      this.loadDeviceList();
    }
  },
  async created() {
  },
  watch: {
    visible(val) {
      if (val) {
        this.loadDeviceList();
      } else {
        // 关闭弹窗时清理资源
        this.clearAllIntervals();
      }
    }
  },
  data() {
    return {
      // 设备列表相关
      deviceListLoading: false,
      deviceList: [],
      barnTreeData: [],
      searchKeyword: '',
      selectedDeviceId: null,
      currentDevice: null,
      
      // 标注相关
      canvas: null,
      ctx: null,
      isDrawing: false,
      startPoint: { x: 0, y: 0 },
      currentMode: 'rectangle',
      autoRefresh: false,
      annotations: [],
      refreshInterval: null,
      // 添加新的数据项
      deviceModalVisible: false,
      deviceForm: {
        relayid: '',
      },
      tempAnnotation: null, // 临时存储当前绘制的标注
      originalImage: null, // 存储原始图片
      isAnnotating: false, // 是否处于标注状态
      isEditing: false, // 是否处于编辑状态
      previousAutoRefresh: false, // 保存标注前的自动刷新状态
      selectedAnnotation: null, // 当前选中的标注
      relayList: [],
      // 提交状态
      loading: false,
      refreshLoading: false, // 添加刷新按钮的 loading 状态
      syncRefLoading: false,
      syncRefTimer: null,

      capImageActionLoading: false, // 添加刷新按钮的 loading 状态
      capImageActionRefTimer: null,

      // 新增图像控制相关数据
      clarityLevel: '50',
      zoomLevel: '50',
      autoCapture: false, // 是否自动拉取图片
      // 新增三个选项
      withAnnotation: '1',
      withDetection: '1',
      withTimestamp: '0',
      ORIGINAL_WIDTH: 1920,  // 1080P 宽度
      ORIGINAL_HEIGHT: 1080, // 1080P 高度
      displayScale: 1,       // 当前显示比例
      queryWifiListRefLoading: false,
      queryWifiListRefTimer: null,

      // 新增继电器相关
      addRelayModalVisible: false,
      addRelayForm: {
        relayid: ''
      },
      refreshRelayLoading: false, // 刷新继电器按钮的loading状态
      refreshFromDbRelayLoading: false, // 从数据库刷新继电器按钮的loading状态
      refreshRelayLoadingTimer : null
    };
  },
  methods: {
    // 加载设备列表
    async loadDeviceList() {
      try {
        this.deviceListLoading = true;
        // 假设这个API返回牛舍下的所有相机设备
        const result = await DeviceSprayCameraApi.list({
          queryOxtallId: this.data.oxtallId 
        });
        
        this.deviceList = result || [];
        
        // 构建树形结构
        this.buildBarnTree();
        
        this.deviceListLoading = false;
      } catch (error) {
        console.error('加载设备列表失败:', error);
        message.error('加载设备列表失败');
        this.deviceListLoading = false;
      }
    },
    
    // 构建牛舍树形结构
    buildBarnTree() {
      this.barnTreeData = this.deviceList.map(device => ({
        title: `设备${device.recordId}${device.lable1 ? ' ['+device.lable1+']' : ''}\n${device.macId}`,
        key: device.recordId,
        isLeaf: true,
        device: device
      }));
    },
    
    // 搜索设备
    handleSearch() {
      if (!this.searchKeyword) {
        this.buildBarnTree();
        return;
      }
      
      const keyword = this.searchKeyword.toLowerCase();
      const filteredDevices = this.deviceList.filter(device => 
        (device.recordId && device.recordId.toString().includes(keyword)) || 
        (device.macId && device.macId.toLowerCase().includes(keyword))
      );
      
      // 使用过滤后的设备列表构建树结构
      this.barnTreeData = filteredDevices.map(device => ({
        title: `设备${device.recordId}${device.lable1 ? ' ['+device.lable1+']' : ''}\n${device.macId}`,
        key: device.recordId,
        isLeaf: true,
        device: device
      }));
    },
    
    // 获取设备状态
    getDeviceStatus(deviceId) {
      const device = this.deviceList.find(d => d.recordId === deviceId);
      return device && device.recordStatus == 1;
    },
    
    // 选择设备
    async handleDeviceSelect(selectedKeys, info) {
      if (selectedKeys.length === 0 || !info.node.isLeaf) return;
      
      const deviceId = selectedKeys[0];
      this.selectedDeviceId = deviceId;
      
      // 查找选中的设备
      const device = this.deviceList.find(d => d.recordId === deviceId);
      if (!device) return;
      
      this.currentDevice = device;
      
      // 清理之前的定时器
      this.clearAllIntervals();
      
      // 重置标注相关状态
      this.annotations = [];
      this.selectedBox = null;
      this.isAnnotating = false;
      this.isEditing = false;

      // 重置图片配置到初始值
      this.clarityLevel = '50';
      this.zoomLevel = '50';
      this.autoCapture = false;
      this.withAnnotation = '1';
      this.withDetection = '1';
      this.withTimestamp = '0';
      
      // 加载设备的继电器列表
      await this.loadRelayList();
      
      // 加载设备图像和标注
      this.loadImage();
      this.loadAnnotations();
      
      // 默认开启自动刷新
      this.autoRefresh = true;
      this.handleAutoRefresh(true);
    },
    
    // 加载继电器列表
    async loadRelayList() {
      try {
        if (!this.currentDevice) return;
        
        const list = await DeviceSprayCameraWifirelayApi.list({
          "recordId": this.currentDevice.recordId
        });
        this.relayList = list || [];
      } catch (error) {
        console.error('加载继电器列表失败:', error);
        message.error('加载继电器列表失败');
      }
    },
    
    // 清理所有定时器
    clearAllIntervals() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
      }
      if (this.syncRefTimer) {
        clearInterval(this.syncRefTimer);
      }
      if (this.capImageActionRefTimer) {
        clearInterval(this.capImageActionRefTimer);
      }
    },
    
    // 更新弹窗可见性
    updateVisible(value) {
      this.$emit('update:visible', value);
      if (!value) {
        this.clearAllIntervals();
      }
    },
    
    // 以下是标注相关方法，与spraycamera-drawing.vue保持一致
    setMode(mode) {
      this.currentMode = mode;
      // 重置绘制状态
      this.isDrawing = false;
      this.selectedBox = null;

      // 重新绘制画布
      if (this.ctx && this.canvas && this.originalImage) {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height);
        this.drawAnnotations();
      }
    },

    async handleManualRefresh() {
      try {
        this.refreshLoading = true;
        if (this.autoCapture) {
          await this.captureImageSync(); // 如果开启了自动拉取，则先拉取图片
        }
        await this.loadImage();
        await this.loadAnnotations();
        message.success('刷新成功');
      } catch (error) {
        message.error('刷新失败');
      } finally {
        this.refreshLoading = false;
      }
    },

    handleAutoRefresh(value) {
      // 先清理已存在的定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
      if (value) {
        this.refreshInterval = setInterval(() => {
          if (this.autoCapture) {
            this.captureImageSync(); // 如果开启了自动拉取，则先拉取图片
          }
          this.loadImage();
          this.loadAnnotations();
        }, 5000);
      }
    },

    handleAnnotatingChange(value) {
      if (value) {
        // 进入标注状态
        this.previousAutoRefresh = this.autoRefresh;
        if (this.autoRefresh) {
          this.autoRefresh = false;
          // 确保清理定时器
          if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
          }
        }
      } else {
        // 退出标注状态
        this.autoRefresh = this.previousAutoRefresh;
        if (this.previousAutoRefresh) {
          this.handleAutoRefresh(true);
        }
      }
    },

    async captureImageSync() {
      if (!this.currentDevice) return;
      
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            config: {
              scale: this.zoomLevel,
              quality: this.clarityLevel,
              marks: this.withAnnotation,
              check: this.withDetection,
              time: this.withTimestamp
            }
          }
        }),
        recordId: this.currentDevice.recordId,
        templateCode: 'spraycamera',
        dictate: 7,
        sceneDictate: 7
      };
      
      try {
        await DeviceCommandDownQueueApi.add2(updateDataRecord);
      } catch (error) {
        message.error('拉取图片失败');
      }
    },

    async loadImage() {
      try {
        if (!this.currentDevice) return;
        
        if (!this.ctx || !this.canvas) {
          this.canvas = this.$refs.canvas;
          if (!this.canvas) return;
          this.ctx = this.canvas.getContext('2d');
        }
        
        let lastOne = await DeviceSprayCameraCaptureimgApi.findLastOne(this.currentDevice.recordId);
        let imageData = lastOne.data.imgUrl ? lastOne.data.imgUrl : 'https://moreycow.oss-cn-hangzhou.aliyuncs.com/vechile/icon/4c4a5be84e8b7ffe35a4192b834f6d2e.jpg';
        const img = new Image();

        img.onload = () => {
          // 计算当前图片相对于1080P的缩放比例,如果是大华的相机，就一直保持不变
          if (this.currentDevice.factory === 'DHUA') {
            this.displayScale = 1;
          } else {
            // 计算当前图片相对于1080P的缩放比例
            this.displayScale = img.width / this.ORIGINAL_WIDTH;
          }

          // 使用图片原始尺寸
          this.canvas.width = img.width;
          this.canvas.height = img.height;
          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
          this.ctx.drawImage(img, 0, 0, img.width, img.height);
          this.originalImage = img;
          if (this.annotations.length > 0) {
            this.drawAnnotations();
          }
        };

        img.onerror = () => {
          message.error('图片加载失败');
        };

        img.src = imageData;
      } catch (error) {
        console.error('加载图片失败:', error);
        message.error('加载图片失败');
      }
    },

    async loadAnnotations() {
      try {
        if (!this.currentDevice) return;
        
        let slotList = [];
        let list = await DeviceSprayCameraSlotApi.list({"recordId": this.currentDevice.recordId});
        
        if (list.data && list.data.length > 0) {
          list.data.forEach(function(item) {
            let pointObj = JSON.parse(item.point) || {};
            let formatItem = {
              points: pointObj.points,
              type: pointObj.type,
              x: pointObj.x,
              y: pointObj.y,
              width: pointObj.width,
              height: pointObj.height,
              relayid: item.relayid,
              relaySwitch: item.wifirelayDTO ? item.wifirelayDTO.relaySwitch : 1,
              relaySwitchText: '',
              status: item.wifirelayDTO ? item.wifirelayDTO.status : 1,
              statusText: "",
              scsId: item.scsId,
              link: item.wifirelayDTO ? item.wifirelayDTO.link : 1,
              linkText: ""
            };
            
            if (item.wifirelayDTO && item.wifirelayDTO.link == 2) {
              formatItem.linkText = "已连";
            } else if (item.wifirelayDTO && item.wifirelayDTO.link == 1) {
              formatItem.linkText = "断连";
            } else {
              formatItem.linkText = "未知状态";
            }

            if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 1) {
              formatItem.relaySwitchText = "喷淋关闭";
            } else if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 2) {
              formatItem.relaySwitchText = "喷淋开启";
            } else if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 3) {
              formatItem.relaySwitchText = "等待喷淋";
            } else if (item.wifirelayDTO && item.wifirelayDTO.relaySwitch == 4) {
              formatItem.relaySwitchText = "喷淋失败";
            } else {
              formatItem.relaySwitchText = "未知状态";
            }
              
            if (item.wifirelayDTO && item.wifirelayDTO.status == 1) {
              formatItem.statusText = "未识别";
            } else if (item.wifirelayDTO && item.wifirelayDTO.status == 2) {
              formatItem.statusText = "识别到牛";
            } else {
              formatItem.statusText = "未识别";
            }

            slotList.push(formatItem);
          });
        }
        
        this.annotations = slotList;
        this.drawAnnotations();
      } catch (error) {
        console.error('加载标注数据失败:', error);
        message.error('加载标注数据失败');
      }
    },

    drawAnnotations() {
      if (!this.ctx || !this.canvas) return;
      
      this.annotations.forEach(annotation => {
        this.drawBox(annotation);
      });
    },

    calculateSize(points) {
      if (!points || points.length < 4) {
        return '0 x 0';
      }
      const width = Math.abs(points[3][0] - points[0][0]);
      const height = Math.abs(points[1][1] - points[0][1]);
      return `${Math.round(width)} x ${Math.round(height)}`;
    },

    drawBox(box) {
      if (!this.ctx) return;

      this.ctx.beginPath();
      // 根据连接状态设置边框颜色
      this.ctx.strokeStyle = box.link === 2 ? '#52c41a' : '#FF4D4F';  // 断连红色，已连绿色
      this.ctx.lineWidth = 2;

      if (box.points && box.points.length === 4) {
        let displayPoints;
        if (this.currentDevice.factory === 'DHUA') {
          // 大华相机：从8192范围转换为像素坐标
          displayPoints = box.points.map(point => [
            // 从8192范围转换回像素坐标
            (point[0] * this.canvas.width) / 8192,
            (point[1] * this.canvas.height) / 8192
          ]);
        } else {
          // 普通相机：将1080P坐标转换为当前显示坐标
          displayPoints = box.points.map(point => [
            point[0] * this.displayScale,
            point[1] * this.displayScale
          ]);
        }
        const points = displayPoints;
        // 计算标注框宽度
        const boxWidth = Math.abs(points[3][0] - points[0][0]);

        // 绘制矩形框
        this.ctx.moveTo(points[0][0], points[0][1]);
        for (let i = 1; i < points.length; i++) {
          this.ctx.lineTo(points[i][0], points[i][1]);
        }
        this.ctx.lineTo(points[0][0], points[0][1]);
        this.ctx.stroke();

        // 第一行：设备ID
        this.ctx.fillStyle = 'rgba(24, 144, 255, 0.2)'
        this.ctx.fillRect(points[0][0], points[0][1] - 80, boxWidth, 20);
        this.ctx.fillStyle = '#fff';
        this.ctx.font = '12px Arial';
        this.ctx.fillText(
          `${box.relayid}`,
          points[0][0] + 5,
          points[0][1] - 65
        );

        // 第二行：连接状态
        this.ctx.fillStyle = box.link === 2 ? 'rgba(82, 196, 26, 0.2)' : 'rgba(255, 77, 79, 0.2)'
        this.ctx.fillRect(points[0][0], points[0][1] - 60, boxWidth, 20);
        this.ctx.fillStyle = '#fff';
        this.ctx.fillText(
          box.link === 2 ? "已连" : "断连",
          points[0][0] + 5,
          points[0][1] - 45
        );

        // 第三行：喷淋状态
        let sprayColor;
        switch (box.relaySwitch) {
          case 1:
            sprayColor = 'rgba(255, 77, 79, 0.2)';  // 喷淋关闭 - 红色
            break;
          case 2:
            sprayColor = 'rgba(82, 196, 26, 0.2)';   // 喷淋开启 - 绿色
            break;
          case 3:
            sprayColor = 'rgba(250, 173, 20, 0.2)';  // 喷淋等待 - 黄色
            break;
          case 4:
            sprayColor = 'rgba(255, 77, 79, 0.2)'; // 喷淋失败 - 红色
            break;
          default:
            sprayColor = 'rgba(217, 217, 217, 0.2)';  // 未知状态 - 灰色
        }
        this.ctx.fillStyle = sprayColor;
        this.ctx.fillRect(points[0][0], points[0][1] - 40, boxWidth, 20);
        this.ctx.fillStyle = '#fff';
        this.ctx.fillText(
          box.relaySwitchText,
          points[0][0] + 5,
          points[0][1] - 25
        );

        // 第四行：识别状态
        this.ctx.fillStyle = box.status === 2 ? 'rgba(82, 196, 26, 0.2)' : 'rgba(255, 77, 79, 0.2)'
        this.ctx.fillRect(points[0][0], points[0][1] - 20, boxWidth, 20);
        this.ctx.fillStyle = '#fff';
        this.ctx.fillText(
          box.statusText,
          points[0][0] + 5,
          points[0][1] - 5
        );
      }
    },

    // 开始绘制标注
    startDrawing(event) {
      if (!this.isAnnotating) return;
      
      const rect = this.canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      
      // 检查是否点击了已有标注
      const clickedAnnotation = this.findAnnotationAtPoint(x, y);
      
      if (clickedAnnotation) {
        // 选中已有标注
        this.selectedBox = clickedAnnotation;
        this.isEditing = true;
        this.deviceForm.relayid = clickedAnnotation.relayid;
        this.deviceModalVisible = true;
      } else {
        // 开始新标注
        this.isDrawing = true;
        this.startPoint = { x, y };
        
        // 清除之前的临时标注
        this.tempAnnotation = null;
        
        // 重绘画布
        if (this.ctx && this.canvas && this.originalImage) {
          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
          this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height);
          this.drawAnnotations();
        }
      }
    },
    
    // 绘制过程中
    drawing(event) {
      if (!this.isAnnotating || !this.isDrawing) return;
      
      const rect = this.canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      
      // 计算矩形的宽高
      let width = x - this.startPoint.x;
      let height = y - this.startPoint.y;
      
      // 如果是正方形模式，使宽高相等
      if (this.currentMode === 'square') {
        const size = Math.max(Math.abs(width), Math.abs(height));
        width = width >= 0 ? size : -size;
        height = height >= 0 ? size : -size;
      }
      
      // 计算矩形的四个角点坐标
      const points = [
        [this.startPoint.x, this.startPoint.y], // 左上
        [this.startPoint.x, this.startPoint.y + height], // 左下
        [this.startPoint.x + width, this.startPoint.y + height], // 右下
        [this.startPoint.x + width, this.startPoint.y] // 右上
      ];
      
      // 创建临时标注对象
      this.tempAnnotation = {
        points: points,
        type: this.currentMode,
        x: this.startPoint.x,
        y: this.startPoint.y,
        width: Math.abs(width),
        height: Math.abs(height)
      };
      
      // 重绘画布
      if (this.ctx && this.canvas && this.originalImage) {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height);
        this.drawAnnotations();
        
        // 绘制临时标注
        this.ctx.beginPath();
        this.ctx.strokeStyle = '#1890ff';
        this.ctx.lineWidth = 2;
        this.ctx.moveTo(points[0][0], points[0][1]);
        for (let i = 1; i < points.length; i++) {
          this.ctx.lineTo(points[i][0], points[i][1]);
        }
        this.ctx.lineTo(points[0][0], points[0][1]);
        this.ctx.stroke();
      }
    },
    
    // 结束绘制
    endDrawing() {
      if (!this.isAnnotating || !this.isDrawing) return;
      
      this.isDrawing = false;
      
      // 如果有临时标注且尺寸足够大，则弹出设备选择框
      if (this.tempAnnotation && 
          this.tempAnnotation.width > 10 && 
          this.tempAnnotation.height > 10) {
        let originalPoints;
        // 根据相机类型进行不同的坐标转换
        if (this.currentDevice.factory === 'DHUA') {
          originalPoints = this.tempAnnotation.points.map(point => [
            Math.round(point[0] / this.canvas.width * 8192),
            Math.round(point[1] / this.canvas.height * 8192)
          ]);
        } else {
          // 将临时标注转换为8192坐标系
          originalPoints = this.tempAnnotation.points.map(point => [
            Math.round(point[0] / this.displayScale),
            Math.round(point[1] / this.displayScale)
          ]);
        }

        this.tempAnnotation.points = originalPoints;
        this.selectedBox = this.tempAnnotation;
        
        // 重置设备表单
        this.deviceForm = {
          relayid: ''
        };
        
        // 显示设备选择弹窗
        this.isEditing = false;
        this.deviceModalVisible = true;
      } else {
        // 清除临时标注
        this.tempAnnotation = null;
        this.selectedBox = null;
        
        // 重绘画布
        if (this.ctx && this.canvas && this.originalImage) {
          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
          this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height);
          this.drawAnnotations();
        }
      }
    },
    
    // 查找点击位置的标注
    findAnnotationAtPoint(x, y) {
      for (let i = 0; i < this.annotations.length; i++) {
        const annotation = this.annotations[i];
        if (annotation.points && annotation.points.length === 4) {
          let displayPoints;
          if (this.currentDevice.factory === 'DHUA') {
            // 大华相机：从8192范围转换为像素坐标
            displayPoints = annotation.points.map(point => [
              // 从8192范围转换回像素坐标
              (point[0] * this.canvas.width) / 8192,
              (point[1] * this.canvas.height) / 8192
            ]);
          } else {
            // 普通相机：将1080P坐标转换为当前显示坐标
            displayPoints = annotation.points.map(point => [
              point[0] * this.displayScale,
              point[1] * this.displayScale
            ]);
          }

          // 检查点是否在矩形内
          const minX = Math.min(...displayPoints.map(p => p[0]));
          const maxX = Math.max(...displayPoints.map(p => p[0]));
          const minY = Math.min(...displayPoints.map(p => p[1]));
          const maxY = Math.max(...displayPoints.map(p => p[1]));
          
          if (x >= minX && x <= maxX && y >= minY && y <= maxY) {
            return annotation;
          }
        }
      }
      return null;
    },
    
    // 处理设备表单提交
    async handleDeviceSubmit() {
      if (!this.deviceForm.relayid) {
        message.warning('请选择wifi继电器');
        return;
      }
      
      try {
        this.loading = true;
        
        if (this.isEditing) {
          // 编辑现有标注
          const index = this.annotations.findIndex(a => a.scsId === this.selectedBox.scsId);
          if (index !== -1) {
            // 更新标注
            await DeviceSprayCameraSlotApi.update({
              scsId: this.selectedBox.scsId,
              relayid: this.deviceForm.relayid,
              recordId: this.currentDevice.recordId
            });
            
            message.success('更新成功');
            
            // 重新加载标注
            await this.loadAnnotations();
          }
        } else {
          // 添加新标注
          const pointData = {
            points: this.selectedBox.points,
            type: this.selectedBox.type,
            x: this.selectedBox.points[0][0],
            y: this.selectedBox.points[0][1],
            width: Math.abs(this.selectedBox.points[3][0] - this.selectedBox.points[0][0]),
            height: Math.abs(this.selectedBox.points[1][1] - this.selectedBox.points[0][1])
          };
          
          await DeviceSprayCameraSlotApi.add({
            point: JSON.stringify(pointData),
            relayid: this.deviceForm.relayid,
            recordId: this.currentDevice.recordId
          });
          
          message.success('添加成功');
          
          // 重新加载标注
          await this.loadAnnotations();
        }
        
        // 关闭弹窗
        this.deviceModalVisible = false;
        this.selectedBox = null;
        this.tempAnnotation = null;
        
      } catch (error) {
        console.error('保存标注失败:', error);
        message.error('保存标注失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 取消设备表单
    handleDeviceCancel() {
      this.deviceModalVisible = false;
      
      if (!this.isEditing) {
        // 如果是新建标注，则清除临时标注
        this.selectedBox = null;
        this.tempAnnotation = null;
        
        // 重绘画布
        if (this.ctx && this.canvas && this.originalImage) {
          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
          this.ctx.drawImage(this.originalImage, 0, 0, this.canvas.width, this.canvas.height);
          this.drawAnnotations();
        }
      }
    },
    
    // 删除标注
    async handleDeviceDelete() {
      if (!this.selectedBox || !this.selectedBox.scsId) {
        message.warning('请先选择要删除的标注');
        return;
      }
      
      try {
        this.loading = true;
        
        await DeviceSprayCameraSlotApi.delete({"scsId" : this.selectedBox.scsId});
        
        message.success('删除成功');
        
        // 关闭弹窗
        this.deviceModalVisible = false;
        this.selectedBox = null;
        
        // 重新加载标注
        await this.loadAnnotations();
        
      } catch (error) {
        console.error('删除标注失败:', error);
        message.error('删除标注失败');
      } finally {
        this.loading = false;
      }
    },
    
    //推送标注到终端 begin
    clearSyncRef(){
      this.syncRefLoading = false;
      clearInterval(this.syncRefTimer);
    },
    checkSync(){
      let that = this;
      this.checkProcess(4, this.clearSyncRef, function(){

      });
    },
    handleSync()
    {
      if (!this.currentDevice) {
        message.warning('请先选择设备');
        return;
      }
      let workerDetailparams = {
        recordId: this.currentDevice.recordId,
        sceneDictate: 4
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSyncCmd();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSyncCmd() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.currentDevice.recordId,
        templateCode: 'spraycamera',
        dictate : 4,
        sceneDictate : 4
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.syncRefLoading = true; //转圈
          this.syncRefTimer = setInterval(this.checkSync, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //推送标注到终端 end
    
  
    // 拉取图片 begin
    captureImageAction() {
      if (!this.currentDevice) {
        message.warning('请先选择设备');
        return;
      }
      let workerDetailparams = {
        recordId: this.currentDevice.recordId,
        sceneDictate: 7
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushCaptureImageAction();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    pushCaptureImageAction() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            config : {
              scale : this.zoomLevel,
              quality : this.clarityLevel,
              marks: this.withAnnotation,
              check: this.withDetection,
              time: this.withTimestamp
            }
          }
        }),
        recordId: this.currentDevice.recordId,
        templateCode: 'spraycamera',
        dictate : 7,
        sceneDictate : 7
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.capImageActionLoading = true; //转圈
          this.capImageActionRefTimer = setInterval(this.checkCapImageAction, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    clearCapImageActionRef(){
      this.capImageActionLoading = false;
      clearInterval(this.capImageActionRefTimer);
    },
    checkCapImageAction(){
      this.checkProcess(7, this.clearCapImageActionRef, function(){

      });
    },

    //拉取图片 end
  
    // 清晰度变更
    handleClarityChange() {
      // 清晰度变更时可以立即应用
      if (this.autoCapture) {
        this.captureImageSync();
      }
    },
    
    // 缩放比例变更
    handleZoomChange() {
      // 缩放比例变更时可以立即应用
      if (this.autoCapture) {
        this.captureImageSync();
      }
    },
    clearQueryWifiListRef() {
      this.queryWifiListRefLoading = false;
      if (this.queryWifiListRefTimer) {
        clearInterval(this.queryWifiListRefTimer);
        this.queryWifiListRefTimer = null;
      }
    },
    checkQueryWifiList() {
      let that = this;
      this.checkProcess(9, this.clearQueryWifiListRef, function() {
  
      });
    },

    queryWifiList() {
      if (!this.currentDevice) {
        message.warning('请先选择设备');
        return;
      }

      let workerDetailparams = {
        recordId: this.currentDevice.recordId,
        sceneDictate: 9
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushQueryWifiListCmd();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    pushQueryWifiListCmd() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.currentDevice.recordId,
        templateCode: 'spraycamera',
        dictate : 9,
        sceneDictate : 9
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.queryWifiListRefLoading = true; //转圈
          this.queryWifiListRefTimer = setInterval(this.checkQueryWifiList, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.currentDevice.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },

    // 打开新增继电器弹窗
    openAddRelayModal() {
      this.addRelayForm.relayid = '';
      this.addRelayModalVisible = true;
    },

    // 提交新增继电器
    async handleAddRelaySubmit() {
      try {
        if (!this.addRelayForm.relayid) {
          message.warning('请输入继电器ID');
          return;
        }
        
        this.loading = true;
        let saveForm = {
          relayid: this.addRelayForm.relayid,
          recordId: this.currentDevice.recordId
        };
        
        let result = DeviceSprayCameraWifirelayApi.add(saveForm);
        result
          .then(result => {
            this.loading = false;
            message.success(result.message || '新增继电器成功');
            this.addRelayModalVisible = false;
            
            // 刷新继电器列表
            this.refreshRelayListFromDB();
          })
          .catch(errorMsg => {
            message.error(errorMsg || '新增继电器失败');
            this.loading = false;
          });
      } catch (error) {
        message.error('新增继电器失败');
        this.loading = false;
      }
    },

    // 取消新增继电器
    handleAddRelayCancel() {
      this.addRelayModalVisible = false;
    },

    // 从数据库刷新继电器列表
    refreshRelayListFromDB() {
      this.refreshFromDbRelayLoading = true;
      DeviceSprayCameraWifirelayApi.list({"recordId": this.currentDevice.recordId})
        .then(list => {
          this.relayList = list;
          message.success('刷新继电器列表成功');
          this.refreshFromDbRelayLoading = false;
        })
        .catch(error => {
          message.error('刷新继电器列表失败');
          this.refreshFromDbRelayLoading = false;
        });
    },

    // 刷新继电器列表
    refreshRelayList() {
      let workerDetailparams = {
        recordId: this.currentDevice.recordId,
        sceneDictate: 9
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { // 处理完成了
            that.pushQueryWifiListCmd1();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    // 推送查询wifi列表命令
    pushQueryWifiListCmd1() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.currentDevice.recordId,
        templateCode: 'spraycamera',
        dictate: 9,
        sceneDictate: 9
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.refreshRelayLoading = true; // 转圈
          this.refreshRelayLoadingTimer = setInterval(this.checkQueryWifiList1, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    checkQueryWifiList1() {
      let that = this;
      this.checkProcess(9, this.clearQueryWifiListRef1, function() {
        that.refreshRelayListFromDB();
      });
    },
    clearQueryWifiListRef1() {
      this.refreshRelayLoading = false;
      if (this.refreshRelayLoadingTimer) {
        clearInterval(this.refreshRelayLoadingTimer);
        this.refreshRelayLoadingTimer = null;
      }
    },
  }
};
</script>

<style scoped>
.annotation-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.annotation-header span {
  color: #666;
}
.device-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 8px;
  width: 100%;
}

.device-info {
  flex: 1;
  white-space: pre-line;
  line-height: 1.5;
  padding: 4px 0;
}

.device-status {
  flex-shrink: 0;
  padding: 4px 0;
}

.device-icon {
  margin-right: 8px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

:deep(.status-tag) {
  margin: 0;
  font-size: 12px;
  line-height: 16px;
  height: 18px;
  padding: 0 4px;
}

/* 添加新样式用于处理长文本 */
:deep(.ant-tree-node-content-wrapper) {
  white-space: pre-line !important;  /* 强制允许换行 */
  height: auto !important;           /* 自适应高度 */
  padding: 4px 8px !important;      /* 增加内边距 */
}

:deep(.ant-tree-node-content-wrapper:hover) {
  background-color: #e6f7ff;        /* 保持悬停效果 */
}

.selected-device {
  font-weight: bold;
  color: #1890ff;
}

.annotation-container {
  padding: 16px;
}

.annotation-tips {
  margin-bottom: 16px;
}

.control-panel {
  margin-bottom: 16px;
}

.tools {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
}

.image-controls {
  margin-bottom: 12px;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.canvas-container {
  width: 100%;
  overflow: auto;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background-color: #000;
  display: flex;
  justify-content: center;
}

canvas {
  max-width: 100%;
  height: auto;
  cursor: crosshair;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.annotation-tips {
  margin-bottom: 16px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

:deep(.ant-alert-message) {
  color: #333;
}


</style>
